<template>
  <div class="hierarchygrid_gadget_tempalte"
       style="width:100%;height:100%"
       :id="id">
    <Portal to="right-disable"
            style="width:100%;height:100%"
            v-loading="loading"
            :disabled="!queryModelDefaultSetting.showSetting">
      <DashboardInterceptConsumer :gadgetId="id"
                                  shadow="never"
                                  class="aui-card--fill flex-1"
                                  @mouseenter="mouseenter(true)"
                                  @mouseleave="mouseenter(false)"
                                  style="width:100%;height: 100%;border:0">
        <el-card shadow="never"
                 class="aui-card--fill flex-1 content-card"
                :style="isHasData?'width:100%;height: 100%;border:0;overflow: visible;':'width:100%;height: 100%;border:0;overflow: hidden;'"
                 >
          <div style="width:100%;height:100%;">
            <div class="cardHeader"
                 @mouseenter="mouseenter(true)"
                 @mouseleave="mouseenter(false)"
                 v-if="(widgetName&& widgetName.trim().length>0) || (gadgetSetting.headerDescription && gadgetSetting.headerDescription.trim().length>0)">
              <GadgetTitle :gadgetSetting="gadgetSetting"
                           :widgetName="widgetName"></GadgetTitle>
              <div>

                <MoreMenu :slicer='slicer'
                          :fitToHeight='fitToHeight'
                          :gadgetId='id'
                          :gadgetType='gadgetInfo.com'
                          @updateQuery="query"
                          :widgetName="widgetName"
                          :businessType="gadgetInfo.businessType"
                          :id="gadgetInfo.id"
                          @showQueryModel="showQueryModel"
                          @fullScreen="fullScreen" />
              </div>
            </div>
            <div class="control-section"
                 style="margin: 10px 10px;width:calc(100% - 10px);height:100%;">
              <div class="content-wrapper"
                   style="width:100%;height:100%;">
                <!-- <div>{{ gadgetSetting.report.associatedFields && gadgetSetting.report.associatedFields.length>0 && gadgetSetting.report.associatedFields[0].fields && gadgetSetting.report.associatedFields[0].fields.length > 0}}</div> -->
                 <ejs-grid v-if="isHasData"
                          :height="comHeight"
                          :dataSource="comDataList"
                          :childGrid="childGrid"
                          :queryCellInfo='customiseCell'
                          :gridLines='gadgetSetting.report.gridLines'
                          :allowResizing="gadgetSetting.report.allowResizing"
                          :allowFiltering="gadgetSetting.report.allowFiltering"
                          :filterSettings="gadgetSetting.report.filterSettings"
                          :allowGrouping="gadgetSetting.report.allowGrouping"
                          :allowPaging="gadgetSetting.report.allowPaging"
                          :toolbar="toolbarItem"
                          :allowTextWrap="gadgetSetting.report.allowTextWrap"
                          :textWrapSettings='wrapSettings'
                          :showColumnChooser="gadgetSetting.report.showColumnChooser"
                          :allowReordering="gadgetSetting.report.allowReordering"
                          :allowSorting="gadgetSetting.report.allowSorting"
                          :load="load"
                          :dataBound="dataBound"
                          :pageSettings="gadgetSetting.report.pageSettings"
                          ref="datagrid"
                          :showColumnMenu='gadgetSetting.report.showColumnMenu'
                          :toolbarClick='toolbarClick'
                          :allowExcelExport='gadgetSetting.report.allowExcelExport'
                          :allowPdfExport='gadgetSetting.report.allowPdfExport'>
                  <e-columns v-if="gadgetSetting.report.associatedFields && gadgetSetting.report.associatedFields.length>0 && gadgetSetting.report.associatedFields[0].fields && gadgetSetting.report.associatedFields[0].fields.length > 0">
                    <e-column v-for="(columnItem, index) in gadgetSetting.report.associatedFields[0].fields"
                              :key="index"
                              :autoFit="index>=5"
                              :width="columnItem.width"
                              :field="columnItem.field"
                              :headerText="columnItem.headerText"
                              :sortComparer="columnItem.type === 'number'?sortComparer:''"
                              :textAlign="columnItem.textAlign"
                              :disableHtmlEncode="columnItem.disableHtmlEncode"

                              :visible="columnItem.visible"
                              :filter="columnItem.allowFiltering">
                    </e-column>
                  </e-columns>
                  <!-- <e-aggregates>
                    <e-aggregate  v-for="(item,i) in AggColumn" :key="i">
                        <e-columns v-if="item&&item.length>0">
                            <e-column v-for="(columnItem, index) in item" :key="index"
                              :type="columnItem.value === 'Sum'?'Custom':columnItem.value === 'Average'?'Custom':columnItem.value"
                              :field="columnItem.field"
                              :customAggregate="columnItem.value=== 'Sum'?customSumFn:columnItem.value==='Average'?customAggregateFn:''"
                              :footerTemplate="columnItem.value==='Sum'?footerTemp:columnItem.value === 'Average'?AverageTemp:returntempate(columnItem.value)" >
                            </e-column>
                        </e-columns>
                    </e-aggregate>
                </e-aggregates> -->
                </ejs-grid>
                <div v-else
                     class="gadget-no-newdata">
                    <div class="widgets-no-data">
                    <div :style="{'fontSize':fontSizeStr1}">{{$t('custom.component.gadget.nodata')}}</div>
                    <!-- <div class="widgets-tip"> <a :href="widgetNoDataWiki"  :style="{'fontSize':fontSizeStr2}"
                         target="black">{{$t('custom.component.gadget.nodatatip')}}</a> </div> -->
                  </div>
                </div>
              </div>
            </div>

          </div>
        </el-card>
        <Lastupdatetime v-if="currentTime"
                        :currentTime="currentTime"
                        :linkedDatasetList="linkedDatasetList"
                        :errorStatus="errorStatus"
                        @updateQuery="query()"></Lastupdatetime>
      </DashboardInterceptConsumer>

    </Portal>
    <model :showSetting="queryModelDefaultSetting.showSetting"
           @queryModelClosed="queryModelClosed"
           @queryModelPreview="queryModelPreview"
           :dataInfo="queryModelDefaultSetting.dataInfo"
           :updateGadget="upgradeGadgetSetting"
           @saveGadgetSetting='saveGadgetSetting' />
    <DrillThrough :gadgetId='id'
                  :pageId='pageId'
                  :slicer="slicer"
                  :queryId="queryId"
                  ref="drill-through"
                  :widgetName='widgetName' />
    <ExportOptionDialog :exportOptionDialogVisible="exportOptionDialogVisible"
                        @closeExportOptionDialog="closeExportOptionDialog"
                        @confirmExport="confirmExport"></ExportOptionDialog>
  </div>
</template>

<script>
import Vue from 'vue'
import mixinGadgetViewModule from '@/mixins/gadget-view-module'
import Lastupdatetime from '@/components/last-update-time/index.vue'
import linkFormat from './template/linkFormat'
import boolFormat from './template/boolFormat'
import progessFormat from './template/progessFormat'
import progessFullFormat from './template/progessfullFormat'
import DrillThroughLinkFormat from './template/DrillThroughLinkFormat'
import ticketLinkFormat from './template/ticketLinkFormat'
import timeEntryLinkFormat from './template/timeEntryLinkFormat'
import { DataTransmit } from './template/dataTransmit'
import dateFormat from './template/dateFormat'
import textFormat from './template/textFormat'
import { defaultGadgetSettingList } from '@/utils/data-json'
import { grids } from 'ejs'
import ExportOptionDialog from '@/components/export-option-dialog/dialog.vue'
import { exportCvs } from '@/utils/exportPdfCvs'
import { get } from 'lodash'
export default {
  mixins: [mixinGadgetViewModule],
  components: { Lastupdatetime, model: () => import('@/components/gadget/query-model/query-model'), ExportOptionDialog },
  data () {
    return {
      currentTime: null,
      childGrid1: { 'dataSource': [{ 'duration': 140, 'start_time': '08/13/2020 13:30:09 EST', 'tenant_name': null, 'user_id': '', 'user_name': null, 'end_time': '08/13/2020 15:50:09 EST', 'id': 334, 'dept_id': '', 'department': null, 'tenant_code': '', 'status': '' }, { 'duration': 46, 'start_time': '08/14/2020 03:45:41 EST', 'tenant_name': 'mspbots.ai', 'user_id': 1285404441592303600, 'user_name': 'Krizza Saavedra', 'end_time': '08/14/2020 04:31:41 EST', 'id': 331, 'dept_id': 1285404348512309200, 'department': 'mspbotsai', 'tenant_code': 1285404348503920600, 'status': 0 }], 'queryString': 'tenant_name', 'allowPaging': true, 'pageSetting': { 'pageSize': 10, 'pageCount': 10 }, 'childGrid': { 'dataSource': [{ 'duration': 140, 'start_time': '08/13/2020 13:30:09 EST', 'tenant_name': null, 'user_id': '', 'user_name': null, 'end_time': '08/13/2020 15:50:09 EST', 'id': 334, 'dept_id': '', 'department': null, 'tenant_code': '', 'status': '' }, { 'duration': 46, 'start_time': '08/14/2020 03:45:41 EST', 'tenant_name': 'mspbots.ai', 'user_id': 1285404441592303600, 'user_name': 'Krizza Saavedra', 'end_time': '08/14/2020 04:31:41 EST', 'id': 331, 'dept_id': 1285404348512309200, 'department': 'mspbotsai', 'tenant_code': 1285404348503920600, 'status': 0 }, { 'duration': 105, 'start_time': '08/13/2020 15:45:36 EST', 'tenant_name': 'mspbots.ai', 'user_id': 1285404426614444000, 'user_name': 'Jim Dong', 'end_time': '08/13/2020 17:30:36 EST', 'id': 328, 'dept_id': 1285404348512309200, 'department': 'mspbotsai', 'tenant_code': 1285404348503920600, 'status': 1 }, { 'duration': 262, 'start_time': '08/13/2020 16:40:21 EST', 'tenant_name': 'mspbots.ai', 'user_id': 1291679010817249300, 'user_name': 'Majalia Jacob', 'end_time': '08/13/2020 21:02:21 EST', 'id': 332, 'dept_id': 1285404348512309200, 'department': 'mspbotsai', 'tenant_code': 1285404348503920600, 'status': 0 }, { 'duration': 10, 'start_time': '08/13/2020 17:03:00 EST', 'tenant_name': 'mspbots.ai', 'user_id': 1285404433652486100, 'user_name': 'Jonalyn Manding', 'end_time': '08/13/2020 17:13:00 EST', 'id': 329, 'dept_id': 1285404348512309200, 'department': 'mspbotsai', 'tenant_code': 1285404348503920600, 'status': 0 }], 'queryString': 'user_name', 'allowPaging': true, 'pageSetting': { 'pageSize': 10, 'pageCount': 10 } } },
      childGrid: {},
      floatNum: 0,
      maxColItem: 0,
      gadgetSetting: {},
      AggColumn: [],
      mixinViewModuleOptions: {
        pageId: this.pageId
      },
      isGridInit: false,
      dataList: [],
      loading: false,
      heightoffset: 60,
      queryModelDefaultSetting: {
        showSetting: false,
        dataInfo: {
          businessId: this.pageId,
          gadgetId: this.id,
          gadgetType: 'hierarchygridgadget',
          gadgetSetting: this._.find(defaultGadgetSettingList, { gadgetType: 'hierarchygridgadget' }).gadgetSetting
        }
      },
      LinkFormat: function () {
        return { template: linkFormat }
      },
      BoolFormat: function () {
        return { template: boolFormat }
      },
      ProgessFormat: function () {
        return { template: progessFormat }
      },
      ProgessfullFormat: function () {
        return { template: progessFullFormat }
      },
      DrillThroughLinkFormat: function () {
        return { template: DrillThroughLinkFormat }
      },
      DateFormat: function () {
        return { template: dateFormat }
      },
      TicketLinkFormat: function () {
        return { template: ticketLinkFormat }
      },
      TimeEntryLinkFormat: function () {
        return { template: timeEntryLinkFormat }
      },
      TextFormat: function () {
        return { template: textFormat }
      },
      conditionFormat: [],
      footerTemp: function () {
        return {
          template: Vue.component('footerTemplate', {
            template: `<span>{{data.Custom}}</span>`,
            data () { return { data: {} } }
          })
        }
      },
      AverageTemp: function () {
        return {
          template: Vue.component('footerTemplate', {
            template: `<span>{{data.Custom}}</span>`,
            data () { return { data: {} } }
          })
        }
      },
      Min: function () {
        return {
          template: Vue.component('avgTemplate', {
            template: `<span>{{data.Min}}</span>`,
            data: function () { return { data: { data: {} } } }
          })
        }
      },
      Max: function () {
        return {
          template: Vue.component('avgTemplate', {
            template: `<span>{{data.Max}}</span>`,
            data: function () { return { data: { data: {} } } }
          })
        }
      },
      Count: function () {
        return {
          template: Vue.component('avgTemplate', {
            template: `<span>{{data.Count}}</span>`,
            data: function () { return { data: { data: {} } } }
          })
        }
      },
      toolbarItem: [], // 'ExcelExport'
      wrapSettings: { wrapMode: 'Both' },
      queryId: '',
      queryDrillthrough: {},
      queryDrillthroughList: [],
      selectFields: [],
      widgetName: '',
      linkedDatasetList: [],
      exportOptionDialogVisible: false
      // childGrid: {
      //   dataSource: [],
      //   queryString: 'tenant_name',
      //   allowPaging: true,
      //   pageSettings: { pageSize: 10, pageCount: 10 },
      //   // columns: [
      //   //   {
      //   //     field: 'OrderID',
      //   //     headerText: 'Order ID',
      //   //     textAlign: 'Right',
      //   //     width: 120
      //   //   },
      //   //   { field: 'ShipCity', headerText: 'Ship City', width: 120 },
      //   //   { field: 'Freight', headerText: 'Freight', width: 120 },
      //   //   { field: 'ShipName', headerText: 'Ship Name', width: 150 }
      //   // ]
      //   childGrid: {
      //     dataSource: [],
      //     queryString: 'user_name'
      //   // columns: [
      //   //   {
      //   //     field: 'CustomerID',
      //   //     headerText: 'Customer ID',
      //   //     textAlign: 'Right',
      //   //     width: 75
      //   //   },
      //   //   { field: 'Address', headerText: 'Address', width: 120 },
      //   //   { field: 'Country', headerText: 'Country', width: 100 }
      //   // ]
      //   }
      // }

    }
  },

  created () {
    // this.query()
    Vue['_this'] = this
    DataTransmit.$on('needData', () => {
      DataTransmit.$emit('giveData', this)
    })
    this.subscribeMessage('runReport', () => {
      this.query(this.refreshCount > 0 ? 'auto' : false)
      this.refreshCount = this.refreshCount + 1
    })
    this.$store.state.isWidget = false
  },
  computed: {
    comHeight () {
      let height=this.gadgetHeight-180
      if(this.gadgetSetting.report.allowPaging){
        height-=50
      }
      return height+'px'
    },
    comDataList () {
      var _self = this
      // return Array.isArray(_self.dataList) ? _self.dataList : []
      var retdata = JSON.parse(JSON.stringify(_self.dataList))
      if (this.gadgetSetting.report.associatedFields && this.gadgetSetting.report.associatedFields[1] && this.gadgetSetting.report.associatedFields[1].value) {
        retdata = this._.uniqBy(retdata, this.gadgetSetting.report.associatedFields[1].value)
      }
      return retdata
    }
  },
  watch: {
    editMode (val) {
      if (!val) {
        this.saveGadgetSetting()
      }
    }
  },
  methods: {
    sortComparer: function (reference, comparer) {
      if (reference === 0 && this.isNull(comparer)) {
        return 1
      }
      if (reference < comparer) {
        return -1
      }
      if (reference > comparer) {
        return 1
      }
      return 0
    },
    isNull (value) {
      if (!value && typeof value !== 'undefined' && value !== 0) {
        return true
      } else {
        return false
      }
    },
    customSumFn: function (data, col) {
      let countLength = 0
      let floatNum = 0
      let num = 0
      for (let index = 0; index < this.dataList.length; index++) {
        let item = this.dataList[index]
        let data = grids.getObject(col.field, item)
        if (!data) continue
        let numData = Number(data)
        countLength += numData
      }
      if (!Number.isInteger(countLength)) { num = countLength.toString().split('.')[1].length }
      if (num < 3) floatNum = num
      else floatNum = 2
      return this.toDecimal(countLength, floatNum)
    },
    toDecimal (x, m) {
      var val = Number(x)
      if (!isNaN(parseFloat(val))) {
        val = val.toFixed(m)
      }
      return val
    },
    customAggregateFn: function (data, col) {
      let count = grids.getObject('count', data)
      let Aggregate = 0
      for (let index = 0; index < this.dataList.length; index++) {
        let item = this.dataList[index]
        let data = grids.getObject(col.field, item)
        if (!data) continue
        let numData = Number(data)
        Aggregate += numData
      }
      let point = 2
      for (let index = 0; index < this.gadgetSetting.report.columns.length; index++) {
        let item = this.gadgetSetting.report.columns[index]
        if (col.field === item.field) {
          point = item.decimalPoint
          break
        }
      }
      // return Aggregate / count
      return this.fomatFloat(Aggregate / count, point)
    },
    fomatFloat (src, pos) {
      return Math.round(src * Math.pow(10, pos)) / Math.pow(10, pos)
    },
    returntempate (type) {
      if (type === 'Sum') {
        return this.Sum
      } else if (type === 'Average') {
        return this.Average
      } else if (type === 'Min') {
        return this.Min
      } else if (type === 'Max') {
        return this.Max
      } else if (type === 'Count') {
        return this.Count
      }
    },
    extractColumn () {
      this.maxColItem = 0
      let parentArr = []
      for (let i = 0; i < 5; i++) {
        let itemArr = []
        for (let index = 0; index < this.gadgetSetting.report.columns.length; index++) {
          let item = this.gadgetSetting.report.columns[index]
          if (item.type === 'number' && item.aggregates.length > 0) {
            if (this.maxColItem < item.aggregates.length) this.maxColItem = item.aggregates.length
            if (item.aggregates[i]) {
              itemArr.push({
                value: item.aggregates[i],
                field: item.field
              })
            }
          }
        }
        if (itemArr.length > 0) parentArr.push(itemArr)
      }
      this.AggColumn = parentArr
    },
    // recordClick (args) {
    //   if (!args.rowData[args.column.foreignKeyField]) {
    //     return
    //   }
    //   var tempAlias = ''
    //   var tempData = ''
    //   var tempList = []
    //   var alias = ''
    //   var pointx = ''
    //   // if (this.queryDrillthroughList.length > 1) {
    //   //   var list = this.selectFields.filter(item => item.queryId === (this.selectFields.find(item => item.alias === args.column.foreignKeyField).queryId))
    //   //   var field = (list.find(i => i.dataType === 'dimension')).field
    //   //   tempList.push({
    //   //     item: '"' + (field || '') + '"' + "='" + (args.rowData['dimesion1'] ? args.rowData['dimesion1'] : '') + "'"
    //   //   })
    //   // } else {
    //   if (this.queryDrillthroughList && this.queryDrillthroughList.length > 0) {
    //     for (let index = 0; index < this.queryDrillthroughList.length; index++) {
    //       const element = this.queryDrillthroughList[index]
    //       tempList.push({
    //         item: '"' + (element.field ? element.field : '') + '"' + "='" + (args.rowData[element.alias] ? args.rowData[element.alias] : '') + "'"
    //       })
    //     }
    //   } else {
    //     if (this.queryDrillthrough && this.queryDrillthrough.alias) {
    //       tempAlias = args.rowData[this.queryDrillthrough.alias]
    //       if (!tempAlias) {
    //         alias = 'dimesion1'
    //       } else {
    //         alias = this.queryDrillthrough.alias
    //       }
    //       pointx = args.rowData[alias]
    //       if (!pointx) {
    //         pointx = ' is null'
    //       } else {
    //         pointx = "= '" + pointx + "'"
    //       }
    //       tempData = '"' + (this.queryDrillthrough.field ? this.queryDrillthrough.field : '') + '"' + pointx
    //     }
    //   }
    //   // }
    //   if (tempList && tempList.length > 0) {
    //     for (let i = 0; i < tempList.length; i++) {
    //       if (i === tempList.length - 1) {
    //         tempData += tempList[i].item
    //       } else {
    //         tempData += tempList[i].item + ' and '
    //       }
    //     }
    //   }
    //   this.queryId = this.selectFields.find(item => item.alias === args.column.foreignKeyField) ? this.selectFields.find(item => item.alias === args.column.foreignKeyField).queryId : ''
    //   if (this.queryId) {
    //     let data = ''
    //     data = tempData
    //     this.findOriginData(data)
    //   }
    // },
    customiseCell (args) {
      var arr = this.conditionFormat
      var column = args.column.field
      var res = arr.filter(item => {
        if (item.dataForm.filters.rules.length !== 0) {
          return item.dataForm.filters.rules[0].key === column
        }
      })
      if (args.data) {
        res.reverse().forEach(it => {
          if (it) {
            if (args.data[it.dataForm.filters.rules[0].key] === null) return
            // eslint-disable-next-line
            var val = args.data[it.dataForm.filters.rules[0].key].toString().replace(/[\$\,]/g, '')
            if (val.includes('%')) {
              // eslint-disable-next-line
              val = Number(val.replace(/%/g, '')) / 100
            } else if (val.indexOf('k') > -1) {
              // eslint-disable-next-line
              val = Number(val.replace(/k/g, '')) * 1000
            }
            if (it.dataForm.filters.rules[0].opt === '=') {
              it.dataForm.filters.rules[0].opt = '=='
            }
            // eslint-disable-next-line
            if (it && eval(Number(val) + it.dataForm.filters.rules[0].opt + Number(it.dataForm.filters.rules[0].value))) {
              args.cell.style.color = it.textColor
              args.cell.style.backgroundColor = it.backgroundColor
            }
          }
        })
      }
    },
    dataBound (args) {
      if (!this.isGridInit) {
        this.isGridInit = true
        this.applyGadgetSetting()
      }
    },
    load (item) {
      this.grid = this.$refs.datagrid
      this.gadgetHeight = this.pageFrom === 'reportLayoutFullScreen' ? window.screen.availHeight-100 :this.pageFromType === 'report' ? ((this.gadgetInfo.h * this.rolHeight) - 30) : this.gadgetInfo.h * (this.rolHeight + 12) - 12 - 30
    },
    applyGadgetSetting () {
      let columnsList = []
      let isAutofit = false
      // process link column
      for (let index = 0; index < this.gadgetSetting.report.columns.length; index++) {
        const element = this.gadgetSetting.report.columns[index]
        // add template and drillThrough
        columnsList.push(element.field)
        if (this.gadgetSetting.report.columns[0] && !this.gadgetSetting.report.columns[0].width) {
          isAutofit = true
        }

        if (element.templateName && element.templateName === 'linkFormat') {
          this.gadgetSetting.report.columns[index].template = this.LinkFormat
        } else if (element.templateName && element.templateName === 'boolFormat') {
          this.gadgetSetting.report.columns[index].template = this.BoolFormat
        } else if (element.templateName && element.templateName === 'progessFormat') {
          this.gadgetSetting.report.columns[index].template = this.ProgessFormat
        } else if (element.templateName && element.templateName === 'dateFormat') {
          this.gadgetSetting.report.columns[index].template = this.DateFormat
        } else if (element.templateName && element.templateName === 'progessFullFormat') {
          this.gadgetSetting.report.columns[index].template = this.ProgessfullFormat
        } else if (element.templateName && element.templateName === 'ticketLinkFormat') {
          this.gadgetSetting.report.columns[index].template = this.TicketLinkFormat
        } else if (element.templateName && element.templateName === 'timeEntryLinkFormat') {
          this.gadgetSetting.report.columns[index].template = this.TimeEntryLinkFormat
        } else if (element.templateName && element.templateName === 'textFormat') {
          this.gadgetSetting.report.columns[index].template = this.TextFormat
        }
        try {
          if (element.drillThrough && element.drillThrough.status) {
            this.gadgetSetting.report.columns[index].template = this.DrillThroughLinkFormat
          }
        } catch (e) {
        }
        // datetime format bugfix
        if (this.gadgetSetting.report.columns[index].type === 'datetime') {
          this.gadgetSetting.report.columns[index].type = 'text'
        }
        if (this.gadgetSetting.report.columns[index].type === 'date') {
          this.gadgetSetting.report.columns[index].type = 'text'
        }
      }
      this.gadgetSetting.report.columns = this.gadgetSetting.report.columns.map(({ visible, field, ...rest }) => {
        const obj = columns.find(i => i.field === field) || {}
        return {
          field,
          visible: obj.visible,
          ...rest
        }
      })
      if (isAutofit) {
        columnsList = Object.keys(this.dataList[0])
        this.grid.ej2Instances.autoFitColumns(columnsList)
      }
      // const columns = get(this.gadgetSetting, 'report.associatedFields[0].fields') || []
      // this.gadgetSetting.report.columns = this.gadgetSetting.report.columns.map(({ visible, field, ...rest }) => {
      //   const obj = columns.find(i => i.field === field) || {}
      //   return {
      //     field,
      //     visible: obj.visible,
      //     ...rest
      //   }
      // })

      this.grid.ej2Instances.setProperties(this.gadgetSetting.report)
    },
    findColumnIndex (arr) {
      for (let index = 0; index < arr.length; index++) {
        const element = arr[index]
        if (element.field === 'Name') {
          return index
        }
      }
      return -1
    },
    saveGadgetSetting () {
      var _self = this
      if (_self.grid) {
        var report = JSON.parse(_self.grid.ej2Instances.getPersistData())
        this._.merge(_self.gadgetSetting.report, report)
        delete _self.gadgetSetting.report
        // grid table , save obj  from json obj
        // const params = {
        //   gadgetSetting: {
        //     report: report
        //   },
        //   gadgetId: this.id
        // }
        // this.$interface.reports.putReportsSettingApi(params).then(({ data: res }) => {
        //   if (res.code !== 0) {
        //     return _self.$message.error(res.msg)
        //   }
        // })
      }
    },
    queryModelClosed () {
      this.queryModelDefaultSetting.showSetting = false
      this.query(true)
    },
    queryModelPreview () {
      this.query(true)
    },
    showQueryModel () {
      this.queryModelDefaultSetting.showSetting = true
    },
    resized (i, newH, newW, newHPx, newWPx) {
      this.gadgetHeight = this.pageFromType === 'report' ? ((newH * this.rolHeight) - this.heightoffset - 30) : newH * (this.rolHeight + 12) - 12 - 30
      this.gadgetWidth = newWPx
    },
    toolbarClick (args) {
      switch (args.item.text) {
        case 'PDF Export':
          if (this.gadgetSetting.report.showExportOption) {
            this.exportOptionDialogVisible = true
          } else {
            (this.$refs['datagrid']).pdfExport()
          }
          break
        case 'Excel Export':
          (this.$refs['datagrid']).excelExport()
          break
        case 'CSV Export':
          // (this.$refs['datagrid']).csvExport()
          exportCvs(this.dataList, this.selectFields)
          break
      }
    },
    query (e) {
      // this.dataList = []
      try {
        this.gadgetSetting.report.columns = []
      } catch (error) { }
      if (e !== 'auto') {
        this.loading = true
        this._.merge(this.gadgetSetting, this.queryModelDefaultSetting.dataInfo.gadgetSetting)
      }
      var _self = this
      var obj = JSON.parse(JSON.stringify(this.slicer))
      let tempObj = this.returnReportLinkParam()
      if (tempObj['name'] && this.slicer['name'] && tempObj['name'] === this.slicer['name']) delete this.slicer['name']
      for (var key in obj) {
        if (key === 'id') {
          delete obj.id
        }
      }
      var param = {
        ...obj,
        code: this.code,
        gadgettype: this.wgadgettype,
        widgetName: this.wName,
        slicer: { ...this.slicer },
        pageId: this.pageId,
        gadgetId: this.id,
        filter: this.getFilterStr(),
        type: this.filterType
      }
      if (!param.pageId) {
        param.type = 'widget'
      }
      _self.queryDrillthrough = {}
      _self.queryDrillthroughList = []
      _self.selectFields = []
      this.isHasData = false
      this.$interface.reports.getReportDataInfo(param)
        .then(({ data: res }) => {
          _self.verifyHasData(res)
          try {
            _self.$parent.$parent.$parent.$parent.$parent.$parent.selectFields = res.selectFields
          } catch (error) {

          }
          _self.heightoffset = 5
          _self.gadgetHeight = this.pageFrom === 'reportLayoutFullScreen' ? window.screen.availHeight-100 :this.pageFromType === 'report' ? ((_self.gadgetInfo.h * _self.rolHeight) - _self.heightoffset - 30) : (_self.gadgetInfo.h * (_self.rolHeight+12)-12) - 30
          if (res.config) {
            _self.gadgetSetting = Object.assign({}, _self._.merge(_self.gadgetSetting, res.config))
            _self.toolbarItem = _self.gadgetSetting.report.toolbar
          }
          if (res.name) {
            _self.widgetName = res.name
          } else if (this.wName) {
            _self.widgetName = this.wName
          } else {
            _self.widgetName = _self.gadgetSetting.headerTitle
          }
          _self.selectFields = res.selectFields
          let objList = []// res.selectFields.find(item => { return item.dataType === 'dimension' })
          for (let i = 0; i < res.selectFields.length; i++) {
            const element = res.selectFields[i]
            if (element.dataType === 'dimension') {
              objList.push(element)
            }
          }
          if (Array.isArray(objList) && objList.length > 1) {
            _self.queryDrillthroughList = objList
          } else {
            _self.queryDrillthrough = objList[0] || {}
            _self.queryId = _self.queryDrillthrough ? _self.queryDrillthrough.queryId : ''
          }
          _self.isGridInit = false
          if (res.data) {
            res.data = JSON.parse(JSON.stringify(res.data))
            _self.dataList = this.formatData(res.data, res.selectFields, 'hierarchygridgadget')
            _self.dataList.forEach(item => {
              for (var key in item) {
                if (item[key] == null) item[key] = ''
              }
            })
            _self.childGridHandler(_self.childGrid, _self.gadgetSetting.report.associatedFields.slice(1), 0)
            // delete _self.childGrid.childGrid.childGrid
            this.extractColumn()
            _self.conditionFormat = res.conditionFormat
            _self.linkedDatasetList = res.datasetSync
          }
          _self.isGridInit = false
        })
        .catch((error) => {
          if (this.wName) {
          this.widgetName = this.wName
          }
          this.isHasData = false
          this.loading = false
          if (error.response && error.response.status === 504) {
            this.errorStatus = '504'
            this.gadgetMessageBus.$emit(this.pageId + 'stopautorefresh')
          }
        }).finally(() => {
          this.currentTime = new Date()
          this.autoRefreshQuery(e)
          this.updateGadgetLoadingStatus(!this.loading)
        })
    },
    childGridHandler (childGrid, associatedFields, index) {
      if (associatedFields.length === 0) return
      if (index + 1 === associatedFields.length) {
        childGrid.dataSource = JSON.parse(JSON.stringify(this.dataList))
      } else {
        childGrid.dataSource = this._.uniqBy(JSON.parse(JSON.stringify(this.dataList)), associatedFields[index + 1].value)
      }
      // columns: [
      //   { field: 'ShipCity', headerText: 'Ship City', width: 120 },
      //   { field: 'Freight', headerText: 'Freight', width: 120 },
      //   { field: 'ShipName', headerText: 'Ship Name', width: 150 }
      // ]
      childGrid.columns = []
      associatedFields[index].fields.filter(its => its.visible).forEach(item => {
        var temp = {
          field: item.field,
          headerText: item.headerText,
          textAlign: item.textAlign,
          filter: item.allowFiltering,
          disableHtmlEncode: item.disableHtmlEncode
        }
        childGrid.columns.push(temp)
      })
      childGrid.queryString = associatedFields[index].value
      childGrid.allowPaging = true
      childGrid.pageSetting = { pageSize: 10, pageCount: 10 }
      if (index + 1 === associatedFields.length) return
      childGrid.childGrid = {}
      this.childGridHandler(childGrid.childGrid, associatedFields, index + 1)

      //                       :headerText="columnItem.headerText"
      //                       :sortComparer="columnItem.type === 'number'?sortComparer:''"
      //                       :textAlign="columnItem.textAlign"
      //                       :disableHtmlEncode="columnItem.disableHtmlEncode"
      //                       :type="columnItem.type"
      //                       :filter="columnItem.filter"
    },
    destroyed () {
      delete Vue['_this']
    },
    remove () {
      this.close()
      if (this.drop.parentNode) {
        this.drop.parentNode.removeChild(this.drop)
      }
    },
    closeExportOptionDialog () {
      this.exportOptionDialogVisible = false
    },
    confirmExport (options) {
      this.$refs.datagrid.pdfExport(options)
      this.exportOptionDialogVisible = false
    }
  },
  destroyed () {
    DataTransmit.$off('needData')
  }

}
</script>
<style lang="scss" scoped>
.content-wrapper {
  position: relative;
  .gadget-no-newdata {
    position: absolute;
    top: 30%;
    left: 0;
    right: 0;
    margin: 0 auto;
    .widgets-no-data {
      display: flex;
      flex-direction: column;
      align-items: center;
      .widgets-tip {
        margin-top: 5px;
      }
    }
  }
}
</style>
<style scoped>
::v-deep .e-parentmsgbar{
  padding-top: 14px!important;
}
::v-deep .e-dlg-content {
  max-height: 120px;
   overflow-y: auto;
}
.hierarchygrid_gadget_tempalte ::v-deep.e-grid .e-summarycell {
  font-size: 13px;
  background-color: #f6f6f6;
  border-color: #e0e0e0;
  color: rgba(0, 0, 0, 0.54);
  font-weight: normal;
}
.el-card ::v-deep .el-card__body {
  width: 100%;
  height: 100%;
  padding: 0px !important;
}

.el-card ::v-deep .el-divider--horizontal {
  margin: 3px 0 !important;
}

.threepoints {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.cardHeader {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 6px 20px;
  border-bottom: 1px solid #eee;
  position: relative;
}

.cardTitle {
  font-size: 16px;
  color: #000;
  font-weight: 700;
  display: inline-block;
  max-width: calc(100% - 30px);
  position: relative;
  top: 2px;
}

.cardIcon {
  font-size: 16px;
  font-weight: 600;
  margin-left: 10px;
  position: relative;
  top: -2px;
}

.toolbar {
  display: flex;
  justify-content: flex-end;
  cursor: pointer;
}

.header {
  display: flex;
  height: 32px;
  justify-content: space-around;
  text-align: center;
  background: no-repeat;
  background-size: cover;
}

.e-grid ::v-deep .e-filter-popup {
  max-height: 300px !important;
  /* overflow-y: auto; */
  top:90px !important;
}

.e-grid ::v-deep .e-checkboxlist {
  height: auto !important;
  overflow-y: visible !important;
}
::v-deep .e-grid .e-ccdlg .e-cc-contentdiv {
  height: 106px;
  overflow-y: auto;
}
</style>
